package org.example.lanchain.controller;

import org.example.lanchain.bean.ApiKey;
import org.example.lanchain.bean.User;
import org.example.lanchain.service.ApiKeyService;
import org.example.lanchain.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * API Key管理控制器
 */
@RestController
@RequestMapping("/api/keys")
@CrossOrigin(origins = "*")
public class ApiKeyController {

    private static final Logger logger = LoggerFactory.getLogger(ApiKeyController.class);

    @Autowired
    private ApiKeyService apiKeyService;
    
    @Autowired
    private UserService userService;

    /**
     * 获取当前用户的所有API Key
     */
    @GetMapping
    public ResponseEntity<Map<String, Object>> getUserApiKeys() {
        try {
            logger.info("开始获取用户API Key列表");
            Long userId = getCurrentUserId();
            logger.info("获取到用户ID: {}", userId);
            
            List<ApiKey> apiKeys = apiKeyService.getUserApiKeys(userId);
            logger.info("查询到 {} 个API Key", apiKeys.size());
            
            // 脱敏处理，不返回完整的API Key
            for (ApiKey apiKey : apiKeys) {
                String maskedKey = maskApiKey(apiKey.getApiKey());
                apiKey.setApiKey(maskedKey);
            }
            
            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("data", apiKeys);
            result.put("message", "获取API Key列表成功");
            
            logger.info("API Key列表获取成功");
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            logger.error("获取API Key列表失败", e);
            Map<String, Object> result = new HashMap<>();
            result.put("success", false);
            result.put("message", "获取API Key列表失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(result);
        }
    }

    /**
     * 创建新的API Key
     */
    @PostMapping
    public ResponseEntity<Map<String, Object>> createApiKey(@RequestBody Map<String, String> request) {
        try {
            Long userId = getCurrentUserId();
            String name = request.get("name");
            
            if (name == null || name.trim().isEmpty()) {
                Map<String, Object> result = new HashMap<>();
                result.put("success", false);
                result.put("message", "API Key名称不能为空");
                return ResponseEntity.badRequest().body(result);
            }
            
            ApiKey apiKey = apiKeyService.createApiKey(userId, name.trim());
            
            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("data", apiKey);
            result.put("message", "API Key创建成功");
            
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            Map<String, Object> result = new HashMap<>();
            result.put("success", false);
            result.put("message", "创建API Key失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(result);
        }
    }

    /**
     * 删除API Key
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<Map<String, Object>> deleteApiKey(@PathVariable Long id) {
        try {
            Long userId = getCurrentUserId();
            boolean deleted = apiKeyService.deleteApiKey(id, userId);
            
            Map<String, Object> result = new HashMap<>();
            if (deleted) {
                result.put("success", true);
                result.put("message", "API Key删除成功");
                return ResponseEntity.ok(result);
            } else {
                result.put("success", false);
                result.put("message", "API Key删除失败，可能不存在或无权限");
                return ResponseEntity.badRequest().body(result);
            }
        } catch (Exception e) {
            Map<String, Object> result = new HashMap<>();
            result.put("success", false);
            result.put("message", "删除API Key失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(result);
        }
    }

    /**
     * 更新API Key名称
     */
    @PutMapping("/{id}/name")
    public ResponseEntity<Map<String, Object>> updateApiKeyName(@PathVariable Long id, 
                                                              @RequestBody Map<String, String> request) {
        try {
            Long userId = getCurrentUserId();
            String name = request.get("name");
            
            if (name == null || name.trim().isEmpty()) {
                Map<String, Object> result = new HashMap<>();
                result.put("success", false);
                result.put("message", "API Key名称不能为空");
                return ResponseEntity.badRequest().body(result);
            }
            
            boolean updated = apiKeyService.updateApiKeyName(id, userId, name.trim());
            
            Map<String, Object> result = new HashMap<>();
            if (updated) {
                result.put("success", true);
                result.put("message", "API Key名称更新成功");
                return ResponseEntity.ok(result);
            } else {
                result.put("success", false);
                result.put("message", "API Key名称更新失败，可能不存在或无权限");
                return ResponseEntity.badRequest().body(result);
            }
        } catch (Exception e) {
            Map<String, Object> result = new HashMap<>();
            result.put("success", false);
            result.put("message", "更新API Key名称失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(result);
        }
    }

    /**
     * 重新生成API Key
     */
    @PostMapping("/{id}/regenerate")
    public ResponseEntity<Map<String, Object>> regenerateApiKey(@PathVariable Long id) {
        try {
            Long userId = getCurrentUserId();
            ApiKey apiKey = apiKeyService.regenerateApiKey(id, userId);
            
            Map<String, Object> result = new HashMap<>();
            if (apiKey != null) {
                result.put("success", true);
                result.put("data", apiKey);
                result.put("message", "API Key重新生成成功");
                return ResponseEntity.ok(result);
            } else {
                result.put("success", false);
                result.put("message", "API Key重新生成失败，可能不存在或无权限");
                return ResponseEntity.badRequest().body(result);
            }
        } catch (Exception e) {
            Map<String, Object> result = new HashMap<>();
            result.put("success", false);
            result.put("message", "重新生成API Key失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(result);
        }
    }

    /**
     * 验证API Key是否有效
     */
    @PostMapping("/validate")
    public ResponseEntity<Map<String, Object>> validateApiKey(@RequestBody Map<String, String> request) {
        try {
            String apiKey = request.get("apiKey");
            boolean valid = apiKeyService.validateApiKey(apiKey);
            
            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("valid", valid);
            result.put("message", valid ? "API Key有效" : "API Key无效");
            
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            Map<String, Object> result = new HashMap<>();
            result.put("success", false);
            result.put("message", "验证API Key失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(result);
        }
    }

    /**
     * 获取当前用户ID
     */
    private Long getCurrentUserId() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null || !authentication.isAuthenticated()) {
            throw new RuntimeException("用户未登录");
        }
        
        Object principal = authentication.getPrincipal();
        if (principal instanceof org.springframework.security.core.userdetails.UserDetails) {
            // 从UserDetails中获取用户名，然后查询用户ID
            String username = ((org.springframework.security.core.userdetails.UserDetails) principal).getUsername();
            User user = userService.findByUsername(username);
            if (user != null) {
                return user.getId();
            } else {
                throw new RuntimeException("用户不存在");
            }
        } else if (principal instanceof Long) {
            return (Long) principal;
        } else if (principal instanceof String) {
            try {
                return Long.parseLong((String) principal);
            } catch (NumberFormatException e) {
                // 可能是用户名，尝试查询
                User user = userService.findByUsername((String) principal);
                if (user != null) {
                    return user.getId();
                } else {
                    throw new RuntimeException("无效的用户信息");
                }
            }
        } else {
            throw new RuntimeException("无法获取用户ID");
        }
    }

    /**
     * 脱敏API Key
     */
    private String maskApiKey(String apiKey) {
        if (apiKey == null || apiKey.length() < 8) {
            return apiKey;
        }
        return apiKey.substring(0, 6) + "****" + apiKey.substring(apiKey.length() - 4);
    }
}